﻿using System;
using System.IO;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace ThePresenter.Windows.Controls
{
	public static class InkCanvasExtensions
	{
		/// <summary>
		/// Gets the background.
		/// </summary>
		/// <param name="canvas">The canvas.</param>
		/// <returns></returns>
		public static byte[] GetBackground(this InkCanvas canvas)
		{
			if (canvas.Background is ImageBrush)
			{
				return (((canvas.Background as ImageBrush).ImageSource as BitmapImage).StreamSource as MemoryStream).ToArray();
			}
			else if (canvas.Background is SolidColorBrush) // null | SolidColorBrush
			{
				Color BGColor = ((SolidColorBrush)canvas.Background).Color;
				return new Byte[] { BGColor.A, BGColor.R, BGColor.G, BGColor.B };
			}
			else
			{
				return null;
			}
		}

		/// <summary>
		/// Sets the background.
		/// </summary>
		/// <param name="canvas">The canvas.</param>
		/// <param name="background">The background.</param>
		public static void SetBackground(this InkCanvas canvas, byte[] background)
		{
			if (background.Length == 4)
				canvas.Background = new SolidColorBrush(System.Windows.Media.Color.FromArgb(background[0], background[1], background[2], background[3]));
			else
			{
				ImageBrush BackgroundBrush = new ImageBrush(Helpers.GetBitmapImageFromStream(new MemoryStream(background)));
				BackgroundBrush.Stretch = Stretch.None;
				BackgroundBrush.AlignmentX = AlignmentX.Left;
				BackgroundBrush.AlignmentY = AlignmentY.Top;
				canvas.Background = BackgroundBrush;
			}			
		}
	}
}
